<template>
  <div>
    <h1>角色管理</h1>
    <div class="actions">
      <el-button type="primary" round plain @click="dialog.visible = true">新增角色</el-button>
    </div>
    <el-divider></el-divider>
    <!-- {{ roleList }} -->
    <el-table :data="state.role.roleList">
      <el-table-column prop="id" label="序号" min-width="80"></el-table-column>
      <el-table-column prop="rolename" label="角色名称" min-width="120"></el-table-column>
      <el-table-column prop="status" label="角色状态" min-width="120">
        <template v-slot="{ row }">
          <el-tag type="primary" v-if="row.status === 1">启用</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180">
        <template v-slot="{ row }">
          <el-button @click="edit(row)" type="primary" plain size="small" round>编辑</el-button>
          <el-button @click="del(row.id)" type="danger" plain size="small" round>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <!-- {{ state.role }} -->
    <el-pagination @size-change="sizeChange" :page-sizes="[2, 5, 10, 15, 20]" @current-change="pageChange" background
      layout="pre,pager,next,sizes,jumper" :total="state.role.roleTotal" v-model:page-size="size"></el-pagination>
  </div>
  <RoleDialog ref="dialog" @updateRoleList="updateRoleList" />
</template>

<script setup>
import RoleDialog from './RoleDialog'
import { roleRemove } from '@/utils/api'
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const { state, dispatch } = store
const dialog = ref(null)
const page = ref(1)
const size = ref(5)

// 自定义事件getRoleTotalAction的处理函数
const updateRoleList = () => {
  dispatch('role/getRoleListAction', { page: page.value, size: size.value })
  dispatch('role/getRoleTotalAction')
}
onMounted(async () => {
  updateRoleList()
})
const pageChange = (num) => {
  page.value = num
  // 重新发送请求
  dispatch('role/getRoleListAction', { page: page.value, size: size.value })
}
const sizeChange = (num) => {
  size.value = num
  // 重新发送请求
  dispatch('role/getRoleListAction', { page: page.value, size: size.value })
}

const edit = (row) => {
  dialog.value.getEditData(row)
}

const del = (id) => {
  ElMessageBox.confirm('确认删除?', '提示', { type: 'waring' }).then(
    async () => {
      const { data } = await roleRemove(id)
      ElMessage({ type: data.code === 200 ? 'success' : 'error', message: data.msg })
      if (data.code === 200) {
        updateRoleList()
      }
    }).catch(() => null)
}

</script>

<style></style>